package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.lib.db.DBConfiguration;
import org.apache.hadoop.mapred.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.Arrays;

public class Step9 extends Configured implements Tool {
    public static  class  Step9Mapper extends Mapper<Text,Text,RecommendShop, NullWritable>{
        /**
         *
         * @param key  user：shop
         * @param value recommendValue
         * @param context
         * @throws IOException
         * @throws InterruptedException
         */
        @Override
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            String[] arr = key.toString().split("[:]");
            System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
            RecommendShop shop = new RecommendShop();
            shop.setUser(Long.parseLong(arr[0]));
            shop.setShop(Long.parseLong(arr[1]));
            shop.setRecommendValue(Double.parseDouble(value.toString()));
            context.write(shop,NullWritable.get());
        }
    }
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        DBConfiguration.configureDB(conf,"com.mysql.cj.jdbc.Driver","jdbc:mysql://server:3306/shop-recommend","root","root");
        String in = conf.get("in");

        Job job = Job.getInstance(conf);
        job.setJobName("step9");
        job.setJarByClass(this.getClass());

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.setInputPaths(job,new Path(in));
        job.setMapperClass(Step9Mapper.class);
        job.setMapOutputKeyClass(RecommendShop.class);
        job.setMapOutputValueClass(NullWritable.class);
        job.setOutputKeyClass(RecommendShop.class);
        job.setOutputValueClass(NullWritable.class);

        job.setOutputFormatClass(DBOutputFormat.class);
        DBOutputFormat.setOutput(job,"t_recommend_shop","user_id","shops_id","recommend_value");



        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step9(),args);

    }
}
